package com.example.weather_app.music;

import android.Manifest;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.weather_app.MainActivity;
import com.example.weather_app.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MusicActivity extends AppCompatActivity implements View.OnClickListener, SongAdapter.OnSongClickListener {

    private static final String TAG = "MusicActivity";
    private static final int MEDIA_PERMISSION_REQUEST_CODE = 200;
    private static final int SELECT_MUSIC_REQUEST_CODE = 300;

    // 界面组件
    private ImageView ivBack, ivAlbumCover, ivPlay, ivPrevious, ivNext, ivAddMusic;
    private TextView tvSongName, tvArtist, tvCurrentTime, tvTotalTime, tvNoMusic;
    private SeekBar sbProgress;
    private RecyclerView rvSongList;
    private SongAdapter songAdapter;

    // 音乐播放相关
    private MediaPlayer mediaPlayer;
    private Handler progressHandler = new Handler();
    private boolean isPlaying = false; // 初始状态设为false
    private List<Song> songList;
    private int currentSongIndex = 0;

    // 进度更新 Runnable
    private Runnable updateProgressRunnable = new Runnable() {
        @Override
        public void run() {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                int currentProgress = mediaPlayer.getCurrentPosition();
                sbProgress.setProgress(currentProgress / 1000); // 转换为秒
                updateTimeDisplay(currentProgress, mediaPlayer.getDuration());
                progressHandler.postDelayed(this, 1000);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);

        initViews();
        initMusicPlayer();
        initSongList();

        // 检查存储权限（适配Android 13+）
        checkAndRequestMediaPermission();
    }

    private void initViews() {
        ivBack = findViewById(R.id.iv_back);

        ivPlay = findViewById(R.id.iv_play);
        ivPrevious = findViewById(R.id.iv_previous);
        ivNext = findViewById(R.id.iv_next);
        ivAddMusic = findViewById(R.id.iv_add_music);
        tvSongName = findViewById(R.id.tv_song_name);
        tvArtist = findViewById(R.id.tv_artist);
        tvCurrentTime = findViewById(R.id.tv_current_time);
        tvTotalTime = findViewById(R.id.tv_total_time);
        tvNoMusic = findViewById(R.id.tv_no_music);
        sbProgress = findViewById(R.id.sb_progress);
        rvSongList = findViewById(R.id.rv_song_list);

        // 设置点击事件
        ivBack.setOnClickListener(this);
        ivPlay.setOnClickListener(this);
        ivPrevious.setOnClickListener(this);
        ivNext.setOnClickListener(this);
        ivAddMusic.setOnClickListener(this);

        // 设置SeekBar监听
        sbProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && mediaPlayer != null) {
                    mediaPlayer.seekTo(progress * 1000); // 转换为毫秒
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.root_layout), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }

    private void initMusicPlayer() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(mp -> {
            // 播放完成，自动播放下一首
            if (!songList.isEmpty()) {
                playNextSong();
            }
        });
    }

    private void initSongList() {
        songList = new ArrayList<>();
        songAdapter = new SongAdapter(songList, this, this);
        rvSongList.setLayoutManager(new LinearLayoutManager(this));
        rvSongList.setAdapter(songAdapter);
        updateNoMusicText();
    }

    /**
     * 检查并请求媒体权限（适配Android 13+）
     */
    private void checkAndRequestMediaPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ 使用新权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_AUDIO)
                    != PackageManager.PERMISSION_GRANTED) {
                requestMediaPermission();
            } else {
                loadLocalMusic();
            }
        } else {
            // 旧版本使用传统权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                requestLegacyStoragePermission();
            } else {
                loadLocalMusic();
            }
        }
    }

    /**
     * 请求Android 13+ 新媒体权限
     */
    private void requestMediaPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_MEDIA_AUDIO)) {
            new AlertDialog.Builder(this)
                    .setTitle("权限请求")
                    .setMessage("需要媒体权限来扫描和播放本地音乐")
                    .setPositiveButton("确定", (dialog, which) -> {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.READ_MEDIA_AUDIO},
                                MEDIA_PERMISSION_REQUEST_CODE);
                    })
                    .setNegativeButton("取消", null)
                    .show();
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_MEDIA_AUDIO},
                    MEDIA_PERMISSION_REQUEST_CODE);
        }
    }

    /**
     * 请求旧版本存储权限
     */
    private void requestLegacyStoragePermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)) {
            new AlertDialog.Builder(this)
                    .setTitle("权限请求")
                    .setMessage("需要存储权限来扫描和播放本地音乐")
                    .setPositiveButton("确定", (dialog, which) -> {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                                MEDIA_PERMISSION_REQUEST_CODE);
                    })
                    .setNegativeButton("取消", null)
                    .show();
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MEDIA_PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MEDIA_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "权限已授予，正在加载音乐...", Toast.LENGTH_SHORT).show();
                loadLocalMusic();
            } else {
                Toast.makeText(this, "权限被拒绝，无法加载本地音乐", Toast.LENGTH_SHORT).show();
                ivAddMusic.setEnabled(false);
                ivAddMusic.setAlpha(0.5f);
            }
        }
    }

    private void loadLocalMusic() {
        new Thread(() -> {
            ContentResolver contentResolver = getContentResolver();
            Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;//访问歌曲的路径
            String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
            String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";

            Cursor cursor = contentResolver.query(
                    uri,
                    null,
                    selection,
                    null,
                    sortOrder
            );

            if (cursor != null && cursor.getCount() > 0) {
                songList.clear();

                while (cursor.moveToNext()) {
                    int titleColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
                    String title = titleColumnIndex != -1 ? cursor.getString(titleColumnIndex) : "未知标题";

                    int artistColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
                    String artist = artistColumnIndex != -1 ? cursor.getString(artistColumnIndex) : "未知艺术家";

                    int durationColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
                    String duration = durationColumnIndex != -1 ? formatTime(cursor.getInt(durationColumnIndex)) : "00:00";

                    int dataColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
                    String data = dataColumnIndex != -1 ? cursor.getString(dataColumnIndex) : "";

                    int albumIdColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
                    long albumId = albumIdColumnIndex != -1 ? cursor.getLong(albumIdColumnIndex) : 0;

                    // 创建歌曲对象并添加到列表
                    Song song = new Song(title, artist, Uri.parse("file://" + data), duration, true, 0, albumId);
                    songList.add(song);
                }

                // 更新UI
                runOnUiThread(() -> {
                    songAdapter.notifyDataSetChanged();
                    updateNoMusicText();
                    if (!songList.isEmpty()) {
                        // 自动加载第一首但不播放
                        playSong(0);
                    }
                });
            }

            if (cursor != null) {
                cursor.close();
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            // 返回主界面
            finish();
        } else if (id == R.id.iv_play) {
            // 播放/暂停
            if (isPlaying) {
                pauseMusic();
            } else {
                if (!checkMusicList()) return;
                startMusic();
            }
        } else if (id == R.id.iv_previous) {
            // 上一首
            if (!checkMusicList()) return;
            playPreviousSong();
        } else if (id == R.id.iv_next) {
            // 下一首
            if (!checkMusicList()) return;
            playNextSong();
        } else if (id == R.id.iv_add_music) {
            // 添加本地音乐
            selectLocalMusic();
        }
    }

    @Override
    public void onSongClick(int position) {
        // 点击歌曲列表项
        currentSongIndex = position;
        playSong(currentSongIndex);
    }

    private boolean checkMusicList() {
        if (songList.isEmpty()) {
            Toast.makeText(this, "没有可用的音乐", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void startMusic() {
        if (mediaPlayer != null) {
            mediaPlayer.start();
            isPlaying = true;
            ivPlay.setImageResource(R.drawable.ic_pause);
            progressHandler.post(updateProgressRunnable);
        }
    }

    private void pauseMusic() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            isPlaying = false;
            ivPlay.setImageResource(R.drawable.ic_play);
            progressHandler.removeCallbacks(updateProgressRunnable);
        }
    }

    private void playSong(int index) {
        if (index < 0 || index >= songList.size()) {
            return;
        }

        Song song = songList.get(index);

        // 更新界面
        tvSongName.setText(song.getTitle());
        tvArtist.setText(song.getArtist());
        tvTotalTime.setText(song.getDuration());

        // 加载并播放音乐
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(this, song.getUri());
            mediaPlayer.prepare();

            // 加载音乐后不自动播放
            isPlaying = false;
            ivPlay.setImageResource(R.drawable.ic_play); // 设置为播放图标

            // 更新进度条
            sbProgress.setMax(mediaPlayer.getDuration() / 1000);
            // 暂停状态不启动进度条更新

            // 更新当前播放歌曲的UI显示
            songAdapter.notifyDataSetChanged();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "播放失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void updateTimeDisplay(int currentTime, int totalTime) {
        tvCurrentTime.setText(formatTime(currentTime));
        tvTotalTime.setText(formatTime(totalTime));
    }

    private String formatTime(int milliseconds) {
        int seconds = (milliseconds / 1000) % 60;
        int minutes = (milliseconds / (1000 * 60)) % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }

    private void playNextSong() {
        if (songList.isEmpty()) return;

        currentSongIndex = (currentSongIndex + 1) % songList.size();
        playSong(currentSongIndex);
    }

    private void playPreviousSong() {
        if (songList.isEmpty()) return;

        currentSongIndex = (currentSongIndex - 1 + songList.size()) % songList.size();
        playSong(currentSongIndex);
    }

    private void selectLocalMusic() {
        // 检查权限后再打开选择界面
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_AUDIO)
                    != PackageManager.PERMISSION_GRANTED) {
                requestMediaPermission();
                return;
            }
        } else {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                requestLegacyStoragePermission();
                return;
            }
        }

        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
        intent.setType("audio/*");
        startActivityForResult(intent, SELECT_MUSIC_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_MUSIC_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            Uri selectedMusicUri = data.getData();
            if (selectedMusicUri != null) {
                // 从URI获取歌曲信息
                String[] projection = {
                        MediaStore.Audio.Media.TITLE,
                        MediaStore.Audio.Media.ARTIST,
                        MediaStore.Audio.Media.DURATION
                };

                Cursor cursor = getContentResolver().query(
                        selectedMusicUri,
                        projection,
                        null,
                        null,
                        null
                );

                if (cursor != null && cursor.moveToFirst()) {
                    int titleColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
                    String title = titleColumnIndex != -1 ? cursor.getString(titleColumnIndex) : "未知标题";

                    int artistColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
                    String artist = artistColumnIndex != -1 ? cursor.getString(artistColumnIndex) : "未知艺术家";

                    int durationColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
                    int durationInt = durationColumnIndex != -1 ? cursor.getInt(durationColumnIndex) : 0;
                    String duration = formatTime(durationInt);

                    // 添加到歌曲列表
                    Song localSong = new Song(
                            title,
                            artist,
                            selectedMusicUri,
                            duration,
                            true,
                            0,
                            0
                    );

                    songList.add(localSong);
                    songAdapter.notifyItemInserted(songList.size() - 1);
                    updateNoMusicText();

                    // 播放新添加的音乐
                    currentSongIndex = songList.size() - 1;
                    playSong(currentSongIndex);
                }

                if (cursor != null) {
                    cursor.close();
                }
            }
        }
    }

    private void updateNoMusicText() {
        if (songList.isEmpty()) {
            tvNoMusic.setVisibility(View.VISIBLE);
        } else {
            tvNoMusic.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放资源
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        progressHandler.removeCallbacks(updateProgressRunnable);
    }
}